#include "utilities.h"

Packet packet;

// =====================================================================
// The setup() function is called once on startup.
// =====================================================================

void setup() {
    pinMode(AMBER_LED_PIN,OUTPUT);
    pinMode(GREEN_LED_PIN,OUTPUT);
    pinMode(STROBE_PIN,OUTPUT);
    pinMode(PIEZO_PIN,OUTPUT);
    pinMode(RED_LED_PIN,OUTPUT);

    // nordic wireless initialization
    initNordic(0);
    
    // initialize wireless packet
    packet.deviceID = 0xbeef;
    packet.sequenceNumber = 0;
    packet.packetType = PACKET_SENSOR_READINGS;
    for(byteValue = 0; byteValue < PACKET_VALUES; byteValue++) {
        packet.data[byteValue] = 0;
    }
    
    digitalWrite(AMBER_LED_PIN,LOW);
    digitalWrite(GREEN_LED_PIN,LOW);
}

void loop() {

    // LEDs off during light measurements
    digitalWrite(AMBER_LED_PIN,HIGH);
    delay(1);
    digitalWrite(AMBER_LED_PIN,LOW);
    delay(1);

    packet.sequenceNumber++;
    if(nordicOK) {

        digitalWrite(RED_LED_PIN,HIGH);
        
        // Append the nordic transmit observer register contents to our packet
        Mirf.readRegister(OBSERVE_TX,(byte*)&(packet.data[7]),1);
    
        // Transmit our new sensor readings
        Mirf.send((byte*)&packet);

        digitalWrite(RED_LED_PIN,LOW);

        uintValue = 100;
        while(--uintValue) { // should probably add a timeout to this loop...
            byteValue = Mirf.getStatus();
            // did we reach the max retransmissions limit?
            if(byteValue & (1 << MAX_RT)) {
                // flash the red LED and play a low tone to signal the communications error
                digitalWrite(RED_LED_PIN,HIGH);
                delay(10);
                //tone(2273,110);
                digitalWrite(RED_LED_PIN,LOW);
                break;
            }
            // was the transmission acknowledged by the receiver?
            if(byteValue & (1 << TX_DS)) {
                //cricket();
                digitalWrite(GREEN_LED_PIN,HIGH);
                delay(10);
                //tone(2273,110);
                digitalWrite(GREEN_LED_PIN,LOW);
                break;
            }
        }

        Mirf.powerUpRx(); // return to Rx mode
        
        delay(100); // wait before sending next packet
    }
}

int main(void) {
    init();
    setup();
    for (;;) {
        loop();
    }
    return 0;
}